package com.itcncp.wechat.app.mini.controller;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.itcncp.common.base.BaseController;
import com.itcncp.common.pingplusplus.model.Event;
import com.itcncp.common.pingplusplus.model.Transfer;
import com.itcncp.common.pingplusplus.model.Webhooks;
import com.itcncp.common.util.JsonUtils;
import com.itcncp.wechat.app.common.constant.ApiConstant;
import com.itcncp.wechat.app.rpc.api.UserAccountInfoService;
import com.itcncp.wechat.app.rpc.api.UserRechangeOpJnlService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 *
 * Created by shuitcncp on 2016/12/10.
 */
@Controller
@RequestMapping("/callback")
@Api(tags = "监听回调管理",value = "", description = "回调信息接口", basePath = "/callback")

public class CallBackController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger( CallBackController.class);

    @Autowired
    private UserRechangeOpJnlService userRechangeOpJnlService;

    @Autowired
    private UserAccountInfoService userAccountInfoService;




    @ApiOperation(value = "微信小程序充值回调")
    @RequestMapping(value = "/wxminiPayRechargeNotify", method = RequestMethod.POST)
    public void wxminiRecharge(HttpServletRequest request) {
        System.err.println("=====================微信小程序充值回调=====================");
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId(ApiConstant.WX_MINI_APPID);
        wxPayConfig.setMchId(ApiConstant.WX_MINI_MCH_ID);
        wxPayConfig.setMchKey(ApiConstant.WX_MINI_MCH_KEY);
        wxPayConfig.setNotifyUrl(ApiConstant.WX_MINI_PAY_NOTIFYURL);
        wxPayConfig.setTradeType("JSAPI");

        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(wxPayConfig);

        try {
            System.err.println("回调订单处理"+ JsonUtils.toJson(request));
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            System.err.println("解析处理"+ xmlResult);
            WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlResult);
            System.err.println("微信支付异步通知请求解析后的对象"+ JsonUtils.toJson(result));
            // 结果正确
            String orderId = result.getOutTradeNo();
            String tradeNo = result.getTransactionId();
            //自己处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
            System.err.println("开始处理订单"+ tradeNo+orderId);
            userRechangeOpJnlService.wxMiniRechargeCallBack(new Long(orderId),tradeNo);
            System.err.println("订单处理成功"+ tradeNo+orderId);
        } catch (Exception e) {
            System.err.println("微信回调结果异常,异常原因"+ e.getMessage());
        }
    }

    @ApiOperation(value = "提现回调")
    @RequestMapping(value = "/pingppCallWithdrawals", method = RequestMethod.POST)
    @ResponseBody
    public void pingppCallWithdrawals(HttpServletRequest request,HttpServletResponse response) throws IOException {

        request.setCharacterEncoding("UTF8");

        // 获得 http body 内容
        BufferedReader reader = request.getReader();
        StringBuffer buffer = new StringBuffer();
        String string;
        while ((string = reader.readLine()) != null) {
            buffer.append(string);
        }

        reader.close();

        //获取异步通知数据
        String eventStr = buffer.toString();

        // 将数据转换成Event对象
        Event event = Webhooks.eventParse(eventStr);

        //将数据转换成Charge对象
        Transfer transfer = (Transfer) Webhooks.getObject(eventStr);

        try {

            //提现订单号
            String orderno = transfer.getOrderNo();

            if ("transfer.succeeded".equals(event.getType())) {

                System.out.println("企业付款成功");

                userAccountInfoService.cashinOpJnlState(orderno,3);

                response.setStatus(200);

            } else if ("transfer.failed".equals(event.getType())) {

                System.out.println("企业付款失败");

                userAccountInfoService.cashinOpJnlState(orderno,1);

                response.setStatus(200);

            } else {

                response.setStatus(500);
            }

        } catch (Exception e) {

            response.setStatus(500);

        }

        response.setStatus(500);
    }



}